import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!!!");
        ExecutorService service = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();
            service.submit(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            System.out.printf("[%s:%d] 客户端上线!!!]\n", clientSocket.getInetAddress(), clientSocket.getPort());
                while (scanner.hasNextLine()) {
                    //1. 获取客户端请求
                    String request = scanner.nextLine();
                    //2. 计算响应
                    String response = process(request);
                    //3. 返回响应
                    printWriter.println(request);
                    printWriter.flush();
                    System.out.printf("[%s:%d] request=%s response=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(),
                            request, response);
                }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            System.out.printf("[%s:%d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
